<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Model\User;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests;

require_once 'resources/org/code/Code.class.php';

class LoginController extends CommonController
{
    public function login()
    {
        if($input = Input::all()){
            $code = new \Code;
            $_code =  $code->get();
            if($_code != strtoupper($input['code'])){
                return back()->with('msg','验证码错误');
            }
            $user = User::first();
            if($user->name != $input['name']){
                return back()->with('msg','用户名不存在');
            }else{
                if($input['pass'] != Crypt::decrypt($user->pass)){
                    return back()->with('msg','密码错误');
                }else{
                    session(['user'=>$user]);
                    return redirect('admin/index');
                }  
            }
        }else{
            session(['user'=>null]);
            return view('admin.login');
        }
        
    }

    public function code()
    {
        $code = new \Code;
        $code->make();
    }

    public function getcode()
    {
        $code = new \Code;
        echo $code->get();
    }
    public function logout(){
        session(['user'=>null]);
        return redirect('admin/login');
    }
    public function crypt(){
        $str = '123456';
        $data =  Crypt::encrypt($str);
        echo $data;
        echo "<br/>";
        echo Crypt::decrypt($data);
    }
    /**修改密码 */
    public function pass(){
        if($input = Input::all()){
           
            $rules = [
                'password'=>'required|between:6,20|confirmed',
            ];

            $message = [
                'password.required'=>'新密码不能为空！',
                'password.between'=>'新密码必须在6-20位之间！',
                'password.confirmed'=>'新密码和确认密码不一致！',
            ];
            $validator = Validator::make($input,$rules,$message);
            if($validator->passes()){
                $user = User::first();
                $_password = Crypt::decrypt($user->pass);
                if($input['password_o']==$_password){
                    $user->pass = Crypt::encrypt($input['password']);
                    $user->update();
                    return back()->with('errors','密码修改成功！');
                }else{
                    return back()->with('errors','原密码错误！');
                }
            }else{
                return back()->withErrors($validator);
            }

        }else{
            return view('admin.pass');
        }
        
    }
}
